package com.example.demo.utils;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RsaUtil {

        /**
         * 获取公钥
         *
         * @param publicKey 公钥
         * @return
         * @throws Exception
         */
        public static PublicKey getPublicKey(String publicKey) throws Exception {
            X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
            KeyFactory factory = KeyFactory.getInstance("RSA");
            return factory.generatePublic(spec);
        }

        /**
         * 获取密钥
         *
         * @param privateKey 私钥
         * @return
         * @throws Exception
         */
        public static PrivateKey getPrivateKey(String privateKey) throws Exception {
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
            KeyFactory factory = KeyFactory.getInstance("RSA");
            return factory.generatePrivate(spec);
        }


}
